<template>
  <div class="pic-upload-container" @mouseenter="imageHovered = true" @mouseleave="imageHovered = false">
    <el-upload class="cover-uploader" :style="{ width: picUrl && !uploadLoading ? 'auto' : (placeholderWidth || '100') + 'px', height: picUrl && !uploadLoading ? 'auto' : (placeholderHeight || '100') + 'px' }" :show-file-list="false" :before-upload="beforeCoverUpload"
        :http-request="handleCoverUpload" drag>
        <template v-if="uploadLoading">
            <CircleProgress :percentage="75" :indeterminate="true" :width="42" :stroke-width="2" :duration="800" />
        </template>
        <template v-else-if="picUrl">
            <img :src="picUrl" class="cover-image" :style="{ width: (placeholderWidth || '100') + 'px', height: (placeholderHeight || '100') + 'px' }" />
        </template>
        <template v-else>
            <div class="upload-placeholder" :style="{ width: (placeholderWidth || '100') + 'px', height: (placeholderHeight || '100') + 'px' }">
                <el-icon class="upload-icon">
                    <Plus />
                </el-icon>
                <div class="upload-text">{{ uploadText }}</div>
            </div>
        </template>
    </el-upload>
    
    <!-- 可编辑模式下的hover按钮覆盖层 -->
    <div v-if="editable && picUrl && imageHovered" class="image-overlay">
      <div class="action-btn" @click="handleUploadClick">
        上传
      </div>
      <div class="action-btn" @click="handleEdit">
        编辑
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPutUrl, putUrlToOss } from '@/api/drama'
import { Upload, Document, Delete, Plus, Close } from '@element-plus/icons-vue'
import CircleProgress from '@/components/common/CircleProgress.vue'
import axios from 'axios';

// 图片上传配置常量
const IMAGE_UPLOAD_CONFIG = {
  MAX_SIZE_MB: 5, // 图片大小限制 8MB
  SUPPORTED_TYPES: ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'],
  ERROR_MESSAGES: {
    INVALID_TYPE: '只能上传图片文件!',
    SIZE_EXCEEDED: `图片大小不能超过 5MB!`,
    UPLOAD_FAILED: '上传失败，请重试'
  }
}

const emit = defineEmits(['start', 'finish', 'edit'])

const props = defineProps({
  defaultUrl: {
    type: String,
    default: ''
  },
  uploadText: {
    type: String,
    default: '上传图片'
  },
  placeholderWidth: {
    type: String,
    default: ''
  },
  placeholderHeight: {
    type: String,
    default: ''
  },
  editable: {
    type: Boolean,
    default: false
  },
  businessId: {
    type: String,
    default: ''
  },
  businessType: {
    type: String,
    default: 'STORYBOARD'
  },
  roles: {
    type: Array,
    default: () => []
  },
  dramaId: {
    type: String,
    default: ''
  }
})

watch(() => props.defaultUrl, (newVal) => {
  picUrl.value = newVal
})

const picUrl = ref(props.defaultUrl || '')

const uploadLoading = ref(false)
const imageHovered = ref(false)

// 处理上传按钮点击 - 打开文件选择器
const handleUploadClick = () => {
  // 触发文件选择器
  const fileInput = document.createElement('input')
  fileInput.type = 'file'
  fileInput.accept = 'image/*'
  fileInput.style.display = 'none'
  
  fileInput.onchange = (event) => {
    const file = event.target.files[0]
    if (file) {
      // 调用原有的上传处理逻辑
      const options = { file }
      handleCoverUpload(options)
    }
  }
  
  document.body.appendChild(fileInput)
  fileInput.click()
  document.body.removeChild(fileInput)
}

// 处理编辑按钮点击
const handleEdit = () => {
  emit('edit', {
    imageUrl: picUrl.value,
    businessId: props.businessId,
    businessType: props.businessType
  })
}

const beforeCoverUpload = (file) => {
  const isImage = IMAGE_UPLOAD_CONFIG.SUPPORTED_TYPES.includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < IMAGE_UPLOAD_CONFIG.MAX_SIZE_MB
  
  if (!isImage) {
    ElMessage.error(IMAGE_UPLOAD_CONFIG.ERROR_MESSAGES.INVALID_TYPE)
    return false
  }
  
  if (!isValidSize) {
    ElMessage.error(IMAGE_UPLOAD_CONFIG.ERROR_MESSAGES.SIZE_EXCEEDED)
    return false
  }
  
  return true
}

const handleCoverUpload = async (options) => {
  const file = options.file
  emit('start')
  uploadLoading.value = true
  try {
    // 显示上传中的预览
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        picUrl.value = reader.result
    }
    const { data } = await getPutUrl(file.type)
    await putUrlToOss(data.url, file)
    // const res = await uploadFile(file)
    if (data && data.fileKey) {
      console.log(data)
      emit('finish', data.fileKey)
      ElMessage.success('上传成功')
    } else {
      throw new Error('上传失败')
    }
    uploadLoading.value = false
  } catch (error) {
    uploadLoading.value = false
    console.error('上传失败:', error)
    ElMessage.error(IMAGE_UPLOAD_CONFIG.ERROR_MESSAGES.UPLOAD_FAILED)
  }
}

// 清除图片
const clearImage = () => {
  picUrl.value = ''
}

// 暴露方法给父组件
defineExpose({
  clearImage
})
</script>
<style scoped>
.pic-upload-container {
  position: relative;
  display: inline-block;
}

.cover-upload-container {
  width: 100%;
}
.cover-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-image {
  width: 100%;
  height: auto;
  object-fit: cover;
  display: block;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fff;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
}

.upload-text {
  color: #525466;
  font-size: 14px;
  margin-top: 8px;
}

/* 可编辑模式下的hover覆盖层 */
.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 8px;
  opacity: 0;
  animation: fadeIn 0.2s ease-in-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.action-btn {
  width: 56px;
  height: 24px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #1C1D29;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(8px);
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: rgba(255, 255, 255, 1);
  border-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-1px);
}

:deep(.el-upload-dragger) {
  width: 100%;
  background-color: transparent;
  border: none;
  height: 100%;
  padding: 0;
}
:deep(.el-upload) {
  height: 100%;
}
:deep(.el-progress__text) {
  display: flex;
  justify-content: center;
  width: 42px;
  min-width: 0;
  font-size: 12px !important;
  color: #0C63FA;
}
.circle-progress-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
